package cn.hloger.spider.demo.newsDemo.handler.news;

import com.alibaba.fastjson.JSONObject;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import cn.hloger.spider.demo.newsDemo.enums.LineEnum;

import java.util.List;

/**
 * TODO
 *
 * @author huanglong
 * @Description TODO
 * @data 2022/9/18
 */
public class NewsWangYiHandler {

    private static String baseUrl = "https://www.163.com/dy/article/";
    private static String listUrl = "https://dy.163.com/v2/article/list.do?pageNo=0&wemediaId=W6170736145098387610&size=10";

    public String getWangYiNews(String title, String tail, LineEnum lineEnum) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> newlist = restTemplate.getForEntity(listUrl, JSONObject.class);
        JSONObject body = newlist.getBody();
        JSONObject data = body.getJSONObject("data").getJSONArray("list").getJSONObject(0);
        //获取静态网页
        String docid = data.getString("docid");
        String url = baseUrl + docid + ".html";
        //爬取网页文字
        return recoverInfo(url, title, tail, lineEnum);
    }

    private String recoverInfo(String url, String title, String tail, LineEnum lineEnum) {
        //这里是加表情包的
        String lineChar = lineEnum.getCode();
        StringBuffer stringBuffer = new StringBuffer();
        JXDocument jxDocument = JXDocument.createByUrl(url);
        // Xpath语句
        String str = "//*[@id=\"content\"]/div[2]/p[2]]";
        // 获取节点集合
        List<JXNode> list = jxDocument.selN(str);
        Element element = list.get(0).asElement();
        for (Node childNode : element.childNodes()) {
            if (!childNode.nodeName().equals("br")) {
                if (childNode.outerHtml().startsWith("365")) {
                    stringBuffer.append(title + lineChar);
                } else {
                    stringBuffer.append(childNode.outerHtml() + lineChar);
                }
                stringBuffer.append(lineChar);
            }
        }
        stringBuffer.append(tail);
        stringBuffer.append(lineChar);
        stringBuffer.append(lineChar);
        return stringBuffer.toString();
    }
}
